package lzm.spring.config;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Inteceptor implements MethodInterceptor {

    private Object obj;

    public Inteceptor() {
    }

    private Inteceptor(Class<?> clazz) {
        this.obj = obj;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(method.isAnnotationPresent(Client.class)) {
            Client annotation = method.getAnnotation(Client.class);
            System.out.println("获取方法标注注解:--------" + annotation.value());
        }
        System.out.println("CGLB-方法前后打印日志:--------before");
        Object invoke = null;
        /*if(methodProxy != null && obj != null) {
            invoke = methodProxy.invoke(obj, objects); //执行对象的方法
        }*/
        System.out.println("CGLB-方法前后打印日志--------after");
        return invoke;
    }

    public Object createCGLBProxy(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        // 设置enhancer对象的父类
        enhancer.setSuperclass(clazz);
        // 设置enhancer的回调对象
        if(clazz.isInterface()) {
            enhancer.setCallback(this);
        } else {
            enhancer.setCallback(new Inteceptor(clazz));
        }

        // 创建代理对象
        return enhancer.create();
    }

}